<?php

require_once( "PhpFaces/Context/FacesContext.php" );


/**
 * A NavigationHandler is passed the outcome string returned by 
 * an application action invoked for this application, and will 
 * use this (along with related state information) to choose the 
 * view to be displayed next.
 * 
 * A default implementation of NavigationHandler must be provided 
 * by the JSF implementation, which will be utilized unless 
 * setNavigationHandler() is called to establish a different one. 
 * This default instance will compare the view identifier of the 
 * current view, the specified action binding, and the specified 
 * outcome against any navigation rules provided in faces-config.xml file(s). 
 * If a navigation case matches, the current view will be changed 
 * by a call to FacesContext.setViewRoot(). Note that a null outcome 
 * value will never match any navigation rule, so it can be used 
 * as an indicator that the current view should be redisplayed.
 */
abstract class PhpFaces_Application_NavigationHandler {
	/** 
	 * Perform navigation processing based on the state information 
	 * in the specified FacesContext, plus the outcome string returned 
	 * by an executed application action. 
	 */
	public abstract function handleNavigation( PhpFaces_Context_FacesContext $facesContext, $fromAction, $fromOutcome );
}

/**
 * The default navigation handler.
 */
class PhpFaces_Application_NavigationHandlerImpl extends PhpFaces_Application_NavigationHandler {
	
	public function __construct() {
		$this->logger = LoggerManager::GetLogger( "PhpFaces.NavigationHandlerImpl" );
	}
	/**
	 * Run the navigation handler on given FacesContext
	 */
	public function handleNavigation( PhpFaces_Context_FacesContext $facesContext, $fromAction, $fromOutcome ) {
		$navigationRules = $facesContext->getNavigationRules();
	
		$fromViewId = ""; // TODO
	
		$this->logger->debug( "handleNavigation from View ID: $fromViewId" );
		
		foreach( $navigationRules as $navigationRule ) {
			$doesFromViewIdMatch = ($navigationRule->fromViewId == null || $navigationRule->fromViewId == $fromViewId);
			$doesFromActionMatch = ($navigationRule->fromAction == null || $navigationRule->fromAction == $fromAction);
			$doesFromOutcomeMatch = ($navigationRule->fromOutcome == null || $navigationRule->fromOutcome == $fromOutcome);
			
			$handlerMatches = $doesFromViewIdMatch && $doesFromActionMatch && $doesFromOutcomeMatch;
			
			if( $handlerMatches )	{
				//print_r( $navigationRule );
				$redirectTo = linkUrl( $navigationRule->toViewId );
				$this->logger->debug( "Redirect to View ID: ".$navigationRule->toViewId );
				//echo "redirectTo = $navigationRule->toViewId = $redirectTo";
				header( "Location: $redirectTo" );
				//virtual( $redirectTo );
				
				exit();
				
			}
		}

	}	
}

?>